import React, {useEffect, useState} from 'react';
import {
  Checkbox,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Popover,
  Space, Switch,
} from 'antd';
import {SourceLogo} from './SourceLogo';
import {InfoCircleOutlined} from '@ant-design/icons';
import {Typography} from 'antd/es';
import {postSearchKey} from '../network/requests';

export const CreateSpider = ({initKey, visible, callback}) => {
  useEffect(()=>{
    form.setFieldsValue({
      'key': initKey,
    });
  }, [initKey]);
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading]=useState(false);
  const [noLimit, setNoLimit]=useState(false);
  const crawlKey = () => {
    form.validateFields().then((r) => {
      setConfirmLoading(true);
      if (noLimit) {
        r.maxCount=0;
      }
      postSearchKey(r).then(() => {
        message.success('任务创建成功');
        callback(true, r.key);
      }).catch(() => {
        message.error('任务创建失败');
      }).finally(()=>{
        setConfirmLoading(false);
      });
    });
  };
  return <Modal
    title={'新建爬虫任务'}
    visible={visible}
    onCancel={() => callback(false)}
    onOk={crawlKey}
    confirmLoading={confirmLoading}
  >
    <Form form={form}>
      <Form.Item
        rules={[
          {
            required: true,
            message: '请输入关键词',
          },
          {
            type: 'string',
            whitespace: true,
            message: '关键词不能为空字符',
          },
        ]}
        initialValue={initKey}
        label={
          <Space>
            关键词
            <Popover content={'多个关键词可以使用空格或加号分割'}>
              <Typography.Text type={'secondary'}>
                <InfoCircleOutlined/>
              </Typography.Text>
            </Popover>
          </Space>}
        name={'key'}
      >
        <Input/>
      </Form.Item>
      <Form.Item
        rules={[{required: true, message: '请至少选择一个任务'}]}
        label={'爬取平台'} name={'platform'}>
        <Checkbox.Group>
          <Checkbox value={'jd'}>
            <SourceLogo noMargin={true} source={'jd'}/></Checkbox>
          <Checkbox value={'dd'}>
            <SourceLogo noMargin={true} source={'dd'}/></Checkbox>
          {/* <Checkbox value={'isbn'}>*/}
          {/*  <SourceLogo noMargin={true} source={'isbn'}/></Checkbox>*/}
        </Checkbox.Group>
      </Form.Item>
      <Form.Item
        rules={[
          {
            required: true,
            message: '请输入爬取条数',
          },
        ]}
        initialValue={1000} label={
          <Space>爬取条数
            <Popover content={'指对于每个平台的爬取数量。由于实际情况，实际爬取条数可能会上下浮动。'}>
              <Typography.Text type={'secondary'}>
                <InfoCircleOutlined/>
              </Typography.Text>
            </Popover>
          </Space>
        } name={'maxCount'}>
        <InputNumber disabled={noLimit} min={1}/>
      </Form.Item>
      <Form.Item label={'不限条数'}>
        <Switch checked={noLimit} onChange={(c)=>setNoLimit(c)}/>
      </Form.Item>
    </Form>
  </Modal>;
};
